//
//  BaseTabBarViewController.m
//  JQLive
//
//  Created by Bruce on 2019/11/26.
//  Copyright © 2019 JQLive. All rights reserved.
//

#import "BaseTabBarViewController.h"
//#import "JQHomeVC.h"
#import "JQMineVC.h"
#import "ViewController.h"

#import "JQAppDelegate.h"
#import "JQHomePageViewController.h"
#import "XLPageViewControllerConfig.h"
#import "JQHomeRoomTagsModel.h"

//#import "UIImage+SVGKit.h"

typedef NS_ENUM(NSInteger,MYMainTabType)
{
    MYMainTabType_Home,    //首页
    MYMainTabType_Mine,           //我的
};

@interface BaseTabBarViewController ()<UITabBarControllerDelegate>

@property (nonatomic,assign) NSInteger sessionUnreadCount;
@property (nonatomic,assign) NSInteger systemUnreadCount;
@property (nonatomic,assign) NSInteger customSystemUnreadCount;
@property (nonatomic,assign) NSInteger  indexFlag;
@property (nonatomic, copy) NSArray *seletedIconArray; //选中按钮图标
@property (nonatomic, strong) LOTAnimationView *animation;
//标题组
@property (nonatomic, copy) NSArray *titles;
@property (nonatomic, copy) NSArray *roomTagIdArr;

@end

@implementation BaseTabBarViewController

+ (instancetype)instance
{
    JQAppDelegate *delegete = (JQAppDelegate *)[UIApplication sharedApplication].delegate;
    UIViewController *vc = delegete.window.rootViewController;
    if ([vc isKindOfClass:[BaseTabBarViewController class]])
    {
        return (BaseTabBarViewController *)vc;
    }
    else
    {
        return nil;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    extern NSString *NTESCustomNotificationCountChanged;
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onCustomNotifyChanged:) name:NTESCustomNotificationCountChanged object:nil];

//    [self roomTagsLoad];
    
    self.seletedIconArray = @[@"home_select",@"mine_select"];
    self.titles = @[@"全部", @"足球", @"篮球", @"娱乐", @"电竞"];
    self.roomTagIdArr = @[@"0", @"1", @"3", @"100", @"40"];
    self.indexFlag = 0;
    
    [self setUpSubNav];// 这句话 很重要  防止 我的点击
//    [self roomTagsLoad];
    
}
- (JQHomePageViewController *)setHomeVC{
    JQHomePageViewController *exampleVC = [[JQHomePageViewController alloc] init];
    exampleVC.title = nil;//@"首页";
    exampleVC.config = [self setConfig];
//    exampleVC.titles = @[@"全部", @"足球", @"篮球", @"娱乐", @"电竞"];
    exampleVC.titles = self.titles;
    exampleVC.roomTagIdArr = self.roomTagIdArr;
    
    return exampleVC;
}

// 请求 导航栏 数据
- (void)roomTagsLoad{
    [MYRequesTool MY_live_roomtags_RequestWithParam:nil successHandle:^(id  _Nonnull response) {
        NSLog(@"response0:%@", response);
        
        JQHomeRoomTagsModel *model = [JQHomeRoomTagsModel mj_objectWithKeyValues:response];
        if (model.code == 200) {
            NSMutableArray *nameArrM = [NSMutableArray arrayWithObject:@"全部"];
            NSMutableArray *roomTagIdArrM = [NSMutableArray arrayWithObject:@"0"];
            for (JQHomeRoomTagsData *data in model.data) {
                [nameArrM addObject:data.name];
                [roomTagIdArrM addObject:data.tag_id];
            }
            self.titles = [nameArrM copy];
            self.roomTagIdArr = [roomTagIdArrM copy];
            // 刷新视图
            [self setUpSubNav];
        }
    } failureHandle:^(NSError * _Nonnull error) {
        NSLog(@"error：%@", error);
    }];
}
- (XLPageViewControllerConfig *)setConfig{
    XLPageViewControllerConfig *config = [XLPageViewControllerConfig defaultConfig];
    
    //标题间距
    config.titleSpace = 8;
    //标题高度
    config.titleViewHeight = 44;
    //在NavigationBar上显示
    config.showTitleInNavigationBar = true;
    //标题选中颜色
    config.titleSelectedColor = MYColorTitleSelected;//kRGBColor(1, 165, 235);//[self colorOfR:1 G:165 B:235];
    //标题选中字体
    config.titleSelectedFont = [UIFont systemFontOfSize:21];
    //标题正常颜色
    config.titleNormalColor = [[UIColor whiteColor] colorWithAlphaComponent:0.6];//kRGBColor(51, 51, 51);// [self colorOfR:51 G:51 B:51];
    
    //标题正常字体
    config.titleNormalFont = [UIFont systemFontOfSize:16];
    //阴影颜色
    config.shadowLineColor = MYColorTitleSelected;//kRGBColor(1, 165, 235);//[self colorOfR:1 G:165 B:235];
    //阴影宽度
    config.shadowLineWidth = 22;
    //阴影末端是直角
    config.shadowLineCap = XLPageShadowLineCapSquare;
    //分割线颜色
    config.separatorLineHidden = true;
//    config.
    
    
//
//    //标题间距
//    config.titleSpace = 8;
//    //标题选中颜色
//    config.titleSelectedColor = MYColorTitleSelected;//[self colorOfR:211 G:60 B:61];
//    //标题选中字体
//    config.titleSelectedFont = [UIFont systemFontOfSize:21];
//    //标题正常颜色
//    config.titleNormalColor = [UIColor whiteColor];//[self colorOfR:34 G:34 B:34];
//    //标题正常字体
//    config.titleNormalFont = [UIFont systemFontOfSize:16];
//    //隐藏动画线条
//    config.shadowLineHidden = true;
//    //分割线颜色
//    config.separatorLineColor = [UIColor whiteColor];//[self colorOfR:231 G:231 B:231];
//
    
    return config;
}
- (void)setConfigNavigationBar {
    UIColor *tintColor = [UIColor blackColor];
    UIColor *titleColor = [UIColor blackColor];
    UIColor *backGroundColor = [UIColor whiteColor];
    UIImage *shadowImage = nil;
    UIStatusBarStyle statusBarStyle = UIStatusBarStyleDefault;
    
    backGroundColor = MYHome_backgroundColor;//[UIColor whiteColor];
    shadowImage = [UIImage imageNamed:@"home_background"];//[[UIImage alloc] init];
  
    tintColor = [UIColor whiteColor];
    titleColor = [UIColor whiteColor];
    backGroundColor = MYColorTitleSelected;// [self colorOfR:48 G:48 B:50];
    statusBarStyle = UIStatusBarStyleLightContent;
    
    
    BaseNavigationController *nav = (BaseNavigationController *)self.navigationController;
    nav.titleColor = titleColor;
    nav.barBackgourndColor = backGroundColor;
    nav.barTintColor = tintColor;
    nav.statusBarStyle = statusBarStyle;
    nav.navigationBar.shadowImage = shadowImage;
}
- (void)setUpSubNav{
    NSArray *titleArray = @[@"首页",@"我"];
    NSArray *iconArray = @[@"home_nor",@"mine_nor"];
//    NSArray *seletedIconArray = @[@"home_select1", @"home_select1"];
//    NSArray *controllersArray = @[@"ViewController",@"JQMineVC"];
    NSArray *controllersArray = @[@"JQHomePageViewController",@"JQMineVC"];//JQHomeItemVC
//    NSArray *controllersArray = @[@"JQHomeItemVC",@"JQMineVC"];
    NSMutableArray *navArray = [NSMutableArray array];
    for (int i = 0; i < controllersArray.count; i++) {
        const char *className = [controllersArray[i] cStringUsingEncoding:NSASCIIStringEncoding];
        Class newClass = objc_getClass(className);
        UIViewController *controller = [newClass new];
        if (i == 0) {
            controller = [self setHomeVC];
        }
        BaseNavigationController *nav = [[BaseNavigationController alloc]initWithRootViewController:controller];
        controller.title = titleArray[i];
        
        UITabBarItem *tabbar = [[UITabBarItem alloc]initWithTitle:titleArray[i] image:[UIImage svgImageNamed:iconArray[i] size:CGSizeMake(30, 30)] selectedImage:nil];
        tabbar.selectedImage = [tabbar.selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        if (i == 0){
            tabbar.selectedImage = [[UIImage svgImageNamed:@"home_select1" size:CGSizeMake(30, 30)] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
        tabbar.image = [tabbar.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//        UIColorFromRGB
        
        if (@available(iOS 13, *)){
               [[UITabBar appearance] setUnselectedItemTintColor:MYColor9];
               [[UITabBar appearance] setTintColor:MYColorYellow];
        }else{
            [tabbar setTitleTextAttributes:@{NSForegroundColorAttributeName: MYColor9} forState:UIControlStateNormal];
            [tabbar setTitleTextAttributes:@{NSForegroundColorAttributeName:MYColorYellow} forState:UIControlStateSelected];
        }
        tabbar.tag = i;
        controller.tabBarItem = tabbar;
        [[UITabBar appearance] setBarTintColor:[UIColor whiteColor]];
        [UITabBar appearance].translucent = NO;
        [navArray addObject:nav];
    }
    self.viewControllers = navArray;//@[homeNAV, mineNAV];
    
//    BaseNavigationController *nav = (BaseNavigationController *)self.viewControllers[0];
//    BaseVC *vc = (BaseVC *)nav.viewControllers[0];
//    [self tabBar:self.tabBar didSelectItem:vc.tabBarItem];
    
}

#pragma mark - Notification
- (void)onCustomNotifyChanged:(NSNotification *)notification
{
//    NTESCustomNotificationDB *db = [NTESCustomNotificationDB sharedInstance];
//    self.customSystemUnreadCount = db.unreadCount;
//    [self refreshSettingBadge];
}
- (void)refreshSessionBadge
{
    BaseNavigationController *nav = self.viewControllers[MYMainTabType_Home];
    nav.tabBarItem.qmui_badgeInteger = self.sessionUnreadCount + self.systemUnreadCount;
}

//新增tabBar点击动效
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    NSArray *array = self.tabBar.subviews;
    UIView *view = array[item.tag+1];
    if (array.count == self.viewControllers.count) {
        view = array[item.tag];
    }
    UIButton *btn = view.subviews.firstObject;
    [self.animation removeFromSuperview];
    NSString *name = self.seletedIconArray[item.tag];
//    CGFloat scale = [[UIScreen mainScreen]scale];
//    name = 3.0 == scale?[NSString stringWithFormat:@"%@@3x",name] : [NSString stringWithFormat:@"%@@2x",name];
    LOTAnimationView *animation = [LOTAnimationView animationNamed:name];
    [btn addSubview:animation];
//    animation.bounds = btn.imageView.bounds;
    animation.bounds = CGRectMake(0, 0, btn.bounds.size.width, btn.bounds.size.width);
//    animation.center = CGPointMake(btn.bounds.size.width/2, btn.bounds.size.height/2);
    [animation playWithCompletion:^(BOOL animationFinished) {

    }];
    self.animation = animation;
    
    NSInteger index = [self.tabBar.items indexOfObject:item];
    if (index != self.indexFlag)
    {
        //执行动画
        NSMutableArray *arry = [NSMutableArray array];
        for (UIView *btn in self.tabBar.subviews)
        {
            if ([btn isKindOfClass:NSClassFromString(@"UITabBarButton")])
            {
                 [arry addObject:btn];
            }
        }
        
        //添加动画
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        //速度控制函数，控制动画运行的节奏
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.duration = 0.3;       //执行时间
        animation.repeatCount = 1;      //执行次数
        animation.removedOnCompletion = NO;
        animation.fillMode = kCAFillModeForwards;           //保证动画效果延续
        animation.fromValue = [NSNumber numberWithFloat:0.8];   //初始伸缩倍数
        animation.toValue = [NSNumber numberWithFloat:1.0];     //结束伸缩倍数
        [[(UIView *)arry[index] layer] addAnimation:animation forKey:nil];
        //移除其他tabbar的动画
        for (int i = 0; i<arry.count; i++)
        {
            if (i != index)
            {
                [[(UIView *)arry[i] layer] removeAllAnimations];
            }
        }
        
        self.indexFlag = index;
    }
}

@end
